package testview.zhen.com.myapplication.tool;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Create by ldr
 * on 2019/8/23 11:35.
 */
public class LockCountDemo {
    public int start = 10;
    public int middle = 90;
    public int end = 200;

    public volatile int tmpAns1 = 0;
    public volatile int tmpAns2 = 0;

    public Lock lock = new ReentrantLock();
    public Condition condition = lock.newCondition();
    public AtomicInteger count = new AtomicInteger(0);


    public int add(int i, int j) {
        try {
            lock.lock();
            int sum = 0;
            for (int tmp = i; tmp < j; tmp++) {
                sum += tmp;
            }
            return sum;
        }
        finally {
            atomic();
            lock.unlock();
        }
    }


    public int sum() throws InterruptedException {
        try {
            lock.lock();
            System.out.print("开始等待~~~~");
            condition.await();
            System.out.print("停止等待~~~~");
            return tmpAns1 + tmpAns2;
        }
        finally {
            lock.unlock();
        }
    }

    public void atomic() {
        if (2 == count.addAndGet(1)) {
            condition.signal();
            System.out.print("解锁成功");
        }
    }

    public void run(){
        final LockCountDemo demo = new LockCountDemo();

        Thread th1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() +
                        " : 开始执行");
                demo.tmpAns1 = demo.add(demo.middle,demo.end+1);
            }
        },"count1");
        Thread th2 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() +
                        " : 开始执行");
                demo.tmpAns2 = demo.add(demo.middle, demo.end + 1);
                System.out.println(Thread.currentThread().getName() +
                        " : calculate ans: " + demo.tmpAns2);
            }
        }, "count2");
        Thread th3 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println(Thread.currentThread().getName() +
                            " : 开始执行");
                    int ans = demo.sum();
                    System.out.println("the total result: " + ans);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "sum");

        th3.start();
        th1.start();
        th2.start();

        try {
            Thread.sleep(3000);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("over");
    }

}


